package core.io.Impl;

import cn.hutool.core.lang.Assert;
import core.io.Resource;
import util.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @Author: Take-off
 * @Description: TODO 根据文件路径 读取文件 InputStream 流
 * @Date: 2023/2/11 4:18 PM
 * @Version: 1.0
 **/
public class ClassPathResource implements Resource {

    private final String path;

    private ClassLoader classLoader;

    public ClassPathResource(String path){
        this(path,(ClassLoader)null);
    }

    public ClassPathResource(String path,ClassLoader classLoader){
        Assert.notNull(path,"路径不能为空");
        this.path = path;
        this.classLoader = ( classLoader != null ?classLoader : ClassUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws IOException {
        //通过 classLoader 读取 path 文件信息
        InputStream inputStream = classLoader.getResourceAsStream(path);
        if (!Optional.ofNullable(inputStream).isPresent()){
            throw new FileNotFoundException(
                    this.path + " cannot be opened because it does not exist");
        }
        return inputStream;
    }
}
